package com.heima.kafka.sample;

import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.TopicPartition;

import java.time.Duration;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;

public class ConsumerQuickStart {
    public static void main(String[] args) {
        // 1. 定义消费者的配置信息
        Properties properties = new Properties();
        // 1.1 kafka地址
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
        // 1.2 key和value反序列化器
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");
        // 1.3 设置消费者所在组
        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"group2");
        // 2. 创建消费者对象
        KafkaConsumer<String,String> consumer = new KafkaConsumer<String, String>(properties);
        // 3. 订阅主题topic
        consumer.subscribe(Collections.singletonList("itheima-topic"));
        // 4. 拉取消息进行消费
        while (true){
            ConsumerRecords<String, String> consumerRecords = consumer.poll(Duration.ofMillis(1000));
            for (ConsumerRecord<String, String> consumerRecord : consumerRecords) {
                System.out.println(consumerRecord.key());
                System.out.println(consumerRecord.value());
                System.out.println(consumerRecord.partition());
                System.out.println(consumerRecord.offset());
                // 处理消息

            }
            // 异步提交偏移量
            try {
                consumer.commitAsync();
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                consumer.commitSync(Duration.ofMillis(1000));
            }
        }

    }
}
